<template>
  <div class="p-4 size-full">
    <SchemaTable
      ref="schemaTableRef"
      :columns="getColumns"
      :fetch-action="getHospitalList"
      header-title="医院管理"
      :scroll="{ y: 600 }"
    >
      <template #toolbar>
        <a-button class="add-btn1" type="primary" @click="openFormModal()">
          新增
        </a-button>
      </template>
    </SchemaTable>
  </div>
</template>

<script setup lang="tsx">
// 组件命名
defineOptions({
  name: 'Hospital',
});

// 导入Vue组合式API
import { ref, onMounted, onBeforeUnmount, useAttrs, useSlots } from 'vue';
import { Modal } from 'ant-design-vue';
import SchemaTable, { ACTION_TYPE } from '@/schema/schema-table';
import { getFormSchemas } from './schema';
import { useTableState } from './hooks';
import { useFormModal } from '@/modals/FormModal';
import {
  getHospitalList,
  deleteHospital,
  updateHospital,
  createHospital,
} from '@/api/hospital.api';
import { isEmpty } from 'lodash-es';

const schemaTableRef = ref();
const [FormModalRender] = useFormModal();

function openFormModal(record) {
  const isCreate = !record;
  
  const formSchemas = getFormSchemas()
  
  FormModalRender.show({
    modalProps: {
      title: `${isCreate ? '新增' : '编辑'}医院`,
      width: 600,
      okText: '保存',
      cancelText: '取消',
      onFinish(state: any) {
        
        if (!state.id) {
          return createHospital(state).then(() => {
            schemaTableRef.value.reload(ACTION_TYPE.CREATE);
          });
        } else {
          return updateHospital(state.id, state).then(() => {
            schemaTableRef.value.reload(ACTION_TYPE.UPDATE);
          });
        }
      },
    },
    formProps: {
      labelCol: { span: 4 },
      span: 24,
      model: {...record, levelId: record.level.id},
      schemas: formSchemas,
    },
  });
}

function openRemoveConfirm(id: number) {
  Modal.confirm({
    title: '您确认要删除这条数据吗？',
    okText: '确认',
    onOk() {
      deleteHospital(id).then(() =>
        schemaTableRef.value.reload(ACTION_TYPE.REMOVE)
      );
    },
    cancelText: '取消',
    class: 'market-confirm',
  });
}

const { getColumns } = useTableState({
  openFormModal,
  openRemoveConfirm,
});

// 生命周期钩子
onMounted(() => {
  console.log('组件已挂载');
});

onBeforeUnmount(() => {
  console.log('组件即将卸载');
});
</script>

<style scoped></style>

